<?php

namespace app\cxapi\controller;

use think\Db;
use app\common\Content;
use app\common\AudioFileAllOperation;

class Transfer extends Request
{
    public function detail()
    {
        try {
            $param = request()->param();
            $map = [
                'create_time' => ['between', [$param['sTime'] - 60 * 10, $param['eTime'] + 60*10]],
                'device_id' => $param['device'],
                'type' => 0
            ];
            $results = Db::name('meeting_speech')->where($map)->order('create_time asc')->select();
            $content = $this->content($results);
            $filename = date("YmdHis", $param['sTime']) . "_" . date("YmdHis", $param['eTime']);
            $this->file($filename, $results);
            return resultArray(['data' => ['content' => $content, 'fileName' => $filename]]);
        } catch (\Exception $e) {
            return resultArray(['error' => '获取转写结果错误']);
        }
    }

    public function download()
    {
        try {
            $param = request()->param();
            $name = $param['fileName'];
            $group = json_decode(cache($name), true);
            $path = $this->filehandle($name, $group);
            download_result_one($path);
        } catch (\Exception $e) {
            return resultArray(['error' => '下载错误']);
        }
    }

    private function file($name,$speech_list){
        $files = [];
        foreach($speech_list as $result){
            $files[] = $result['formatname'];
        }
        cache($name, json_encode($files), 86400);       
    }

    private function content($speech_list)
    {
        $filecontent = new Content();
        $FRAME = 0.2;
        foreach ($speech_list as $val) {
            if (!json_decode($val['lvsr_data'], true)['list']) {
                continue;
            }
            foreach (json_decode($val['lvsr_data'], true)['list'] as $sentence) {
                $filecontent->push($sentence['txt'], (explode("-", $sentence['time'])[1] - explode("-", $sentence['time'])[0]) * $FRAME, str_replace(['角色','未标记'],['','-1'],$sentence['speaker']));
            }
        }
        return $filecontent->getArr();
    }

    private function filehandle($name, $group){
        $fileGroup = array_map(function($data){
            return "/home/wwwroot/default/data/box-recording/$data";
        }, $group);
        $file_wav = "/home/wwwroot/default/data/$name.wav";
        $file_mp3 = "/home/wwwroot/default/data/$name.mp3";
        AudioFileAllOperation::mergerWaves($fileGroup, $file_wav);
        AudioFileAllOperation::wavTrans2Another($file_wav, $file_mp3);
        @unlink($file_wav);
        return $file_mp3;
    }
}
